package com.ikingtech.platform.business.message.service.router;

import com.ikingtech.framework.sdk.enums.message.MessageSendChannelEnum;
import com.ikingtech.framework.sdk.enums.system.user.UserSocialTypeEnum;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.push.common.*;
import lombok.RequiredArgsConstructor;

import java.util.Map;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
public class WechatMiniMessageRouter implements MessageRouter {

    @Override
    public RouteResult route(RouteRequest request) {
        PushRequest body = this.parseBody(request.getChannelId(),
                request.getChannelTemplateId(),
                request.getRedirectDefinitinoMap(),
                request.getParamDefinitionMap(),
                request.getMessageWrapper());
        DeliverResult result = PushManager.wechatMini().send(body, Tools.Coll.filter(request.getTarget().getSocials(), social -> request.getChannelId().equals(social.getSocialId()) && UserSocialTypeEnum.WECHAT_MINI_OPEN_ID.equals(social.getSocialType())).get(0).getSocialNo());
        return new RouteResult(Tools.Str.replace(request.getTemplateContent().replace(".DATA", ""), "{{", "}}", Tools.Bean.convertToMap(request.getMessageWrapper())),
                Tools.Coll.convertList(body.getBody().getRedirectTo(), MessageRedirect::getRedirectLink),
                result.getSuccess(),
                result.getCause());
    }

    private PushRequest parseBody(String wechatMiniId,
                                  String wechatMiniMessageTemplateId,
                                  Map<String, String> redirects,
                                  Map<String, String> paramDefinitions,
                                  Object messageWrapper) {
        Map<String, Object> messageParamMap = Tools.Json.objToMap(messageWrapper);
        PushRequest pushRequest = new PushRequest();
        MessageBody body = new MessageBody();
        pushRequest.setAppConfigId(wechatMiniId);
        pushRequest.setTemplateId(wechatMiniMessageTemplateId);
        if (Tools.Coll.isNotBlankMap(messageParamMap)) {
            pushRequest.setTemplateParams(this.convertToTemplateParam(paramDefinitions, messageParamMap));
        }
        Boolean ignoreRedirect = (Boolean) messageParamMap.get("ignoreRedirect");
        if (Boolean.TRUE.equals(ignoreRedirect)) {
            body.setRedirectTo(this.createMessageRedirect(redirects, messageParamMap));
        }
        pushRequest.setBody(body);
        return pushRequest;
    }

    /**
     * 获取消息发送渠道
     *
     * @return 消息发送渠道
     */
    @Override
    public MessageSendChannelEnum channel() {
        return MessageSendChannelEnum.WECHAT_MINI_SUBSCRIBE;
    }
}
